/*******************************************************************************
 * Copyright (c) 2011 LegSem.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl-3.0.txt
 * 
 * Contributors:
 *     LegSem - initial API and implementation
 ******************************************************************************/
package com.legsem.legstar.jca;

import javax.resource.ResourceException;
import javax.resource.spi.LocalTransaction;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.legstar.messaging.RequestException;

/**
 * This is a Container managed type transaction.
 * <p/>
 * No need to notify Container Manager because it initiates the methods itself.
 * 
 */
public class LegStarManagedLocalTransactionImpl implements LocalTransaction {

    private LegStarManagedConnection managedConnection;

    /** Logger. */
    private final Log log = LogFactory.getLog(getClass());

    public LegStarManagedLocalTransactionImpl(
            LegStarManagedConnection managedConnection) {
        this.managedConnection = managedConnection;
    }

    public void begin() throws ResourceException {
    }

    public void commit() throws ResourceException {
        try {
            if (log.isDebugEnabled()) {
                log.debug("Transaction commit requested");
            }
            if (managedConnection.getHostConnection().isOpen()) {
                managedConnection.getHostConnection().commitUOW();
            } else {
                log.warn("Transaction commit requested but connection is closed");
            }
        } catch (RequestException e) {
            throw new ResourceException(e);
        }
    }

    public void rollback() throws ResourceException {
        try {
            if (log.isDebugEnabled()) {
                log.debug("Transaction rollback requested");
            }
            if (managedConnection.getHostConnection().isOpen()) {
                managedConnection.getHostConnection().rollbackUOW();
            } else {
                log.warn("Transaction rollback requested but connection is closed");
            }
        } catch (RequestException e) {
            throw new ResourceException(e);
        }
    }

}
